package com.example.private_auto_install.toolby;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

public class MyRSAEnCoderTools {
    private String licenseKey = "sxxsy-levy";
    private String licenseName = "山西欣数源科技有限公司-国家生源地助学贷款授权文件";
    private String licenseType = "user";
    private String licenseFilePath = "D:\\license";
    private String licenseSourceFileName = "sxxsy.txt";
    private String expireday = "2016-09-30";
    private Integer clientCount = 100;
    private String licenseFileName = "levy.lic";
    private String machineCode = "DKDH8273DJJH839DKKSAYUWCBNXM283";

    private String[] getFileContent() {
        String[] defaultFileContent = new String[]{"LICENSEID=" + this.licenseKey, "LICENSENAME=" + this.licenseName, "LICENSETYPE=" + this.licenseType, "EXPIREDAY=" + this.expireday, "CLIENTCOUNT=" + this.clientCount, "CHECKMACHINECODE=YES", "MACHINECODE=" + this.machineCode};
        return defaultFileContent;
    }

    public MyRSAEnCoderTools(String licenseKey, String licenseName, String licenseType, String expireday, Integer clientCount, String licensePath, String licenseSourceFileName, String distLicenseFileName, String machCode) {
        this.licenseKey = licenseKey;
        this.licenseName = licenseName;
        this.licenseType = licenseType;
        this.licenseFilePath = licensePath;
        this.expireday = expireday;
        this.clientCount = clientCount;
        this.licenseSourceFileName = licenseSourceFileName;
        this.licenseFileName = distLicenseFileName;
        this.machineCode = machCode;
    }

    public void initLicensePath() {
        System.out.println("-----------开始初始化路径-----------");

        try {
            this.initLicensePath(this.licenseFilePath, this.licenseSourceFileName, this.getFileContent());
        } catch (Exception var2) {
            var2.printStackTrace();
            System.out.println(var2.getMessage());
        }

        System.out.println("-----------初始化路径完成-----------");
    }

    public void genLicenseFile() {
        System.out.println("-----------开始生成证书-----------");
        String filePath = this.licenseFilePath + File.separator + this.licenseFileName;

        try {
            this.genLicenseFile(this.licenseFilePath, this.licenseSourceFileName, this.licenseFileName, this.getFileContent());
            boolean f = this.checkLicenseFile(filePath, this.machineCode, new Date());
            System.out.println("证书check结果:" + f);
        } catch (Exception var3) {
            var3.printStackTrace();
            System.out.println(var3.getMessage());
        }

        System.out.println("-----------生成证书完成-----------");
    }

    private void initLicensePath(String licensePath, String sourceFileName, String[] defaultLicenseContent) throws Exception {
        File file = new File(licensePath + File.separator + sourceFileName);
        File filePath = new File(licensePath);
        if (filePath.exists()) {
            System.out.println("路径已经存在:" + filePath.getAbsolutePath());
        } else {
            filePath.mkdirs();
        }

        if (file.exists()) {
            System.out.println("License源文件已经存在:" + file.getAbsolutePath());
        } else {
            List<String> lines = new ArrayList();
            int j = 0;

            for (int len = defaultLicenseContent.length; j < len; ++j) {
//                if (StringUtils.isNotEmpty(defaultLicenseContent[j])) {
//                    lines.add(defaultLicenseContent[j]);
//                }
                if (defaultLicenseContent[j] != null && defaultLicenseContent[j].length() > 0) {
                    lines.add(defaultLicenseContent[j]);
                }

            }

            FileUtils.writeLines(file, "UTF-8", lines);
            System.out.println("初始化路径完成:" + file.getAbsolutePath());
        }

    }

    private void genLicenseFile(String licensePath, String sourceFileName, String licenseFileName, String[] defaultLicenseContent) throws Exception {
        PrivateKey privateKey = RSAEnCoder.getPrivateKey("168471656040682369067024842962822083298669539093986092465366127155720426564118469603013433851342957534348138682751573582625566160744115198034661810651722103097169587486100008061472372333707837160018287515262612680876274406409425481997533147443089198863298280210902750052071080616127252265650629071271842635449", "150901371025529646290988179678709460820582255579217413062879326125625226668399261526101203807643534082751795733019254351698826384607184496620698500219378204253214947180327085393185504812856350810804446056695865412260029797508072007855612286308169717837624067781580510271891701740762168471560451778085144503393");
        File file = new File(licensePath + File.separator + sourceFileName);
        File licenseFile = new File(licensePath + File.separator + licenseFileName);
        File filePath = new File(licensePath);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }

        if (!file.exists()) {
            this.initLicensePath(licensePath, sourceFileName, defaultLicenseContent);
        }

        if (!file.exists()) {
            throw new Exception("没有获取License加密的源文件");
        } else {
            if (licenseFile.exists()) {
                licenseFile.delete();
            }

            FileInputStream fis = new FileInputStream(file);
            if (fis.available() == 0) {
                throw new FileNotFoundException("License加密的源文件为空");
            } else {
                fis.close();
                byte[] sByte = FileUtils.readFileToByteArray(file);
                if (sByte.length == 0) {
                    throw new FileNotFoundException("License加密的源文件为空");
                } else {
                    byte[] encoderData = RSAEnCoder.encryptRSA(sByte, privateKey);
                    String sign = RSAEnCoder.sign(encoderData, privateKey);
                    byte[] signBytes = ("\n" + sign).getBytes();
                    byte[] raw = new byte[encoderData.length + signBytes.length];
                    System.arraycopy(encoderData, 0, raw, 0, encoderData.length);
                    System.arraycopy(signBytes, 0, raw, encoderData.length, signBytes.length);
                    byte[] encoderaw = RSAEnCoder.encryptRSA(raw, privateKey);
                    FileUtils.writeByteArrayToFile(licenseFile, encoderaw);
                    System.out.println("License生成完成,路径:" + licenseFile.getAbsolutePath());
                }
            }
        }
    }

    private boolean checkLicenseFile(String licenseFilePath, String machCode, Date currentDate) throws Exception {
        PublicKey publicKey = RSADeCoder.getPublicKey("168471656040682369067024842962822083298669539093986092465366127155720426564118469603013433851342957534348138682751573582625566160744115198034661810651722103097169587486100008061472372333707837160018287515262612680876274406409425481997533147443089198863298280210902750052071080616127252265650629071271842635449", "65537");
        File licenseFile = new File(licenseFilePath);
        if (!licenseFile.exists()) {
            System.out.println("没有获取License文件");
            return false;
        } else {
            FileInputStream fis = FileUtils.openInputStream(licenseFile);
            if (fis.available() == 0) {
                System.out.println("License加密文件为空");
                fis.close();
                return false;
            } else {
                fis.close();
                byte[] encoderData = FileUtils.readFileToByteArray(licenseFile);
                byte[] sbytes = RSADeCoder.decryptRSA(encoderData, publicKey);
                byte[] firstEncoderData = (byte[]) null;
                byte[] secondSignData = (byte[]) null;
                int index = 0;

                for (int len = sbytes.length; index < len; ++index) {
                    if (sbytes[index] == 10) {
                        firstEncoderData = new byte[index];
                        secondSignData = new byte[len - index - 1];
                        System.arraycopy(sbytes, 0, firstEncoderData, 0, firstEncoderData.length);
                        System.arraycopy(sbytes, index + 1, secondSignData, 0, secondSignData.length);
                        if (this.isArrayByteBase64(secondSignData)) {
                            break;
                        }
                    }
                }

                String sign = new String(secondSignData);
                boolean verify = RSADeCoder.verify(firstEncoderData, sign, publicKey);
                if (!verify) {
                    System.out.println("License签名校验无效,请确认这证书的有效性.");
                    return false;
                } else {
                    byte[] textBytes = RSADeCoder.decryptRSA(firstEncoderData, publicKey);
                    System.out.println("授权文件详情:" + new String(textBytes));
                    HashMap<String, String> prop = this.genDataFromArrayByte(textBytes);
                    String licenseType = (String) prop.get("LICENSETYPE");
                    System.out.println("授权软件给:" + (String) prop.get("LICENSENAME"));
                    System.out.println("截止日期:" + (String) prop.get("EXPIREDAY"));
                    System.out.println("type:" + (String) prop.get("LICENSETYPE"));
                    if (StringUtils.isEmpty(licenseType)) {
                        System.out.println("License校验无效,无法获取证书类型.");
                        return false;
                    } else {
                        String licenseKey = (String) prop.get("LICENSEID");
                        if (!licenseKey.startsWith(licenseKey)) {
                            System.out.println("License校验无效,请确认这证书的有效性.");
                            return false;
                        } else {
                            String machineCode = (String) prop.get("MACHINECODE");
                            String needCheckMachineCode = (String) prop.get("CHECKMACHINECODE");
                            if ("YES".equals(needCheckMachineCode) && !machineCode.equals(machCode)) {
                                System.out.println("License校验,机器码与当前机器码不同");
                                return false;
                            } else {
                                if ("user".equals(licenseType)) {
                                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
                                    String expireDay = (String) prop.get("EXPIREDAY");
                                    Date expireDate = df.parse(expireDay);
                                    if (currentDate.after(expireDate)) {
                                        System.out.println("License已经过期,请联系厂商重新获取License授权.");
                                        return false;
                                    }
                                }

                                String printClientCount = (String) prop.get("CLIENTCOUNT");
                                if (StringUtils.isEmpty(printClientCount)) {
                                    System.out.println("授权终端数量必须填写");
                                    return false;
                                } else if (!StringUtils.isNumeric(printClientCount.trim())) {
                                    System.out.println("授权终端数量必须为数字");
                                    return false;
                                } else {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private HashMap<String, String> genDataFromArrayByte(byte[] b) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(b)));
        HashMap<String, String> data = new HashMap();
        String str = null;

        while ((str = br.readLine()) != null) {
            if (StringUtils.isNotEmpty(str)) {
                str = str.trim();
                int pos = str.indexOf("=");
                if (pos > 0) {
                    if (str.length() > pos + 1) {
                        data.put(str.substring(0, pos).trim().toUpperCase(), str.substring(pos + 1).trim());
                    } else {
                        data.put(str.substring(0, pos).trim().toUpperCase(), "");
                    }
                }
            }
        }

        return data;
    }

    private boolean isArrayByteBase64(byte[] b) {
        try {
            return Base64.isArrayByteBase64(b);
        } catch (Exception var3) {
            return false;
        }
    }
}

